/*
 * Created by Federico Pisarello - SisDev Software (c) 2012 - fpisarello@sisdevsoft.com
 */

var popForm = 'sucursalesPop.php';
var actionForm = 'sucursalesAction.php';

var joDataSucursal;
var oTable;

/** Variable of tracking the IndexPK **/
var actionPK = undefined;
var action = undefined;

function $_init()
{	
	var gaiSelected;
	
	$(document).ready(function() {
    	oTable = $('#dt_sucursales').dataTable( {
					"bJQueryUI": true,
					"sPaginationType": "two_button",
					"bInfo": false,
					"bLengthChange": false,
					"bProcessing": true,
					"bAutoWidth": false,
					"bServerSide": true,
					"sAjaxSource": actionForm + "?accion=search",
					"fnRowCallback": function( nRow, aData, iDisplayIndex ) {
						if ( jQuery.inArray(aData[0], gaiSelected) != -1 )
						{
					        $(nRow).addClass('row_selected');
						}
						return nRow;
					},
					"aoColumns": [
					  			null,
					  			null,
					  			null,
					  			null
					  		]

				});
    	
    	$('#dt_sucursales tbody td img').live( 'click', function () {
    		var nTr = $(this).parents('tr')[0];
    		if (oTable.fnIsOpen(nTr) )
    		{
    			/* This row is already open - close it */
    			this.src = "images/details_open.png";
    			oTable.fnClose( nTr );
    		}
    		else
    		{            
    			/* Open this row */            
    			this.src = "images/details_close.png";            
    			oTable.fnOpen( nTr, fnFormatDetailsSucursal(oTable, nTr), 'details' );        
    		}    
    	});
    	
    	/* Click event handler */
    	$('#dt_sucursales tbody tr').live('click', function () {
    		var aData = oTable.fnGetData(this);
    		var iId = aData[0];
    		actionPK = aData[0];
    		
    		gaiSelected =  [];
    		if ( $(this).hasClass('row_selected') ) {
	            $(this).removeClass('row_selected');
	            actionPK = undefined;
	        }
	        else {
	            oTable.$('tr.row_selected').removeClass('row_selected');
	            $(this).addClass('row_selected');
	            gaiSelected[gaiSelected.length++] = iId;
	        }
    	} );

	});
	
	$("#sucursalesDialog").dialog({
		autoOpen:false, 
		height:'auto', 
		width:540, 
		modal: true,
		closeOnEscape: false,
		position : ['center',10],
		dialogClass:'no-close',
		beforeClose: function() { $_ClearSucursalesPopForm(); },
		open: function() {
			$('#sucursalesDialog').css('background-color','#4f4233');
		}
	});
	
	//Add Click for All Buttons in Search Form
	$("#btnAgregar").click( function(e) {
		addProxyShow();
    });
	
	$('#btnEditar').click( function(e) {
		editProxyShow();
	});	
}

function fnFormatDetailsSucursal(oTableSucursal, nTr){
	var aData = oTableSucursal.fnGetData(nTr);
	var sOut = "";
	var paramData =  "accion=searchSucursalDetalle&idSucursal=" + aData[0];
	
    $.ajax({
        type: 'POST',
        url: actionForm,
        data: paramData,
        async: false,
		dataType: 'html',
        success: function(strHtml)
                            {
        						sOut = '<table cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;">';
        						sOut += strHtml;
        						sOut += '</table>';
                            }
    });
		
	return sOut;
}

function $_initPop()
{
	//Add Click for All Buttons in Pop Form
	$('#btnCerrar').click( function(e) {
		$('#sucursalesDialog').dialog('close');
	});
	$('#btnGuardar').click( function(e) {
		$('#sucursalesPopForm').submit();
	});
	
	$('.numeric').numeric();
	$('#codSucursal').blur(function(){
		if($(this).val().length > 4)
			$(this).val('');
		else {
			var codSucursal = "0000"+$(this).val(); 
			$(this).val(codSucursal.substring(codSucursal.length-4));
		}
	});
		
	//Populate User Data	
	if(action == iConst.EDIT)
	{
		$('#descripcion').val(joDataSucursal.descripcion);
		$('#codSucursal').val(joDataSucursal.codSucursal);
	}
	
	$_ValidatorSetDefaults();
	$_initPopValidator();	
}

function addProxyShow()
{
	//Reset State of action and IndexPK
	actionPK = undefined;
	action = iConst.NEW;
	oTable.$('tr.row_selected').removeClass('row_selected');
	$('#sucursalesDialog').load(popForm).dialog('open');
}

function editProxyShow()
{
	if(actionPK === undefined)
	{
		$_showMessage('ALERT', 'ALERTA', 'Seleccione una Sucursal de la Grilla');
		return;
	}
	
	action = iConst.EDIT;
	var paramData =  "accion=" + iConst.EDIT + "&idSucursal=" + actionPK;
	
    $.ajax({
        type: 'POST',
        url: actionForm,
        data: paramData,
		dataType: 'json',
        success: function(jsonObj)
                            {
        						joDataSucursal = jsonObj;
        						//Open Pop Dialog
        						$('#sucursalesDialog').load(popForm).dialog('open');
                            }
        });
	
return true;
}

function $_saveSucursal(action)
{
	$("#btnGuardar").attr('disabled','disabled');
	
	var paramData = 'accion=addOrEdit&' + $("#sucursalesPopForm").serialize();
	
	if(action == iConst.EDIT)
		paramData += '&idSucursal=' + actionPK;
	
    $.ajax({
        type: 'POST',
        url: actionForm,
        data: paramData,
		dataType: 'json',
        success: function(jsonObj){
            if(jsonObj.status === 'OK'){
				$_showMessage('OK', jsonObj.status, jsonObj.msg);
				$('#sucursalesDialog').dialog('close');
				oTable.fnDraw();
			}
			else
				$_showMessage('ERR', jsonObj.status, jsonObj.msg);
            $("#btnGuardar").removeAttr('disabled');
        }
    });

return true;
}

function $_initPopValidator()
{
	$('#sucursalesPopForm').validate({
		submitHandler: function() {
			$_saveSucursal(action);
		}, 		
		rules: {
			descripcion: {required: true,minlength: 1},
			codSucursal: {required: true,minlength: 1}
		},
		messages: {
			descripcion: {required: '',minlength: ''},
			codSucursal: {required: '',minlength: ''}
		}
	});	
}

function $_ClearSucursalesPopForm()
{	
	$("#sucursalesDialog").empty();
}